package com.yang.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yang.domain.dto.LoginFormDTO;
import com.yang.domain.dto.Result;
import com.yang.domain.dto.UserDTO;
import com.yang.domain.entity.User;
import com.yang.enums.AppHttpCodeEnum;
import com.yang.exception.ServiceException;
import com.yang.mapper.UserMapper;
import com.yang.service.IUserService;
import com.yang.utils.RegexUtils;
import com.yang.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.yang.constants.RedisConstants.*;
import static com.yang.constants.SystemConstants.USER_NICK_NAME_PREFIX;
import static com.yang.enums.AppHttpCodeEnum.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yang
 * @since 2022-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private UserMapper userMapper;


    @Override
    public String sendCode(String phone) {

        Assert.isFalse(RegexUtils.isPhoneInvalid(phone),PHONE_CHECK_ERROR.getMsg());

        String code = RandomUtil.randomNumbers(6);

        System.out.println("发送短信验证码成功，验证码："+ code);

        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone,code,LOGIN_CODE_TTL, TimeUnit.MINUTES);

        return code;
    }

    @Override
    public String login(LoginFormDTO loginForm) {
        String phone = loginForm.getPhone();

        Assert.isFalse(RegexUtils.isPhoneInvalid(phone),PHONE_CHECK_ERROR.getMsg());

        String code = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);

        if (code== null || !code.equals(loginForm.getCode())){
            throw new ServiceException(COED_ERROR.getMsg());
        }

        User user = userMapper.findUserByPhone(phone);

        if (user == null){
            user = createUserWithPhone(phone);
        }

        String token = LOGIN_CODE_KEY + UUID.randomUUID().toString(true);

        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);

        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO,new HashMap<>(),
                CopyOptions
                        .create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString())
        );

        String tokenKey = LOGIN_USER_KEY + token;
        stringRedisTemplate.opsForHash().putAll(tokenKey,userMap);
        stringRedisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);

        return token;

    }
    @Override
    public void sign() {
        //1.拿到要签到的用户id
        Long userId = UserHolder.getUser().getId();

        //2.获取日期
        LocalDateTime now = LocalDateTime.now();
        String day = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));

        //3.拼接出key: 前缀名+userid+day
        String key = USER_SIGN_KEY + userId + day;

        //4.获取当月的天数
        int dayOfMonth = now.getDayOfMonth();

        //5.写入到redis setBit key offset 1
        stringRedisTemplate.opsForValue().setBit(key,dayOfMonth-1,true);

    }

    @Override
    public int signCount() {
        //1.获取当前登录的用户
        Long userId = UserHolder.getUser().getId();

        //2.获取日期后缀
        LocalDateTime now = LocalDateTime.now();
        String keySuffix = now.format(DateTimeFormatter.ofPattern("yyyyMM"));

        //3.拼接key
        String key = USER_SIGN_KEY + userId + keySuffix;

        //4.获取今天是本月的第几天
        int dayOfMonth = now.getDayOfMonth();

        //5.获取本月到今天为止的所有签到记录，返回一个十进制的数字
        List<Long> result = stringRedisTemplate.opsForValue().bitField(key,
                BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0)
        );

        //6.判断是否签到过
        if (result == null || result.isEmpty()){
            return 0;
        }
        Long num = result.get(0);
        if (num == null || num == 0){
            return 0;
        }

        //7.有签到记录，进行统计
        int count = 0;
        while (true){
            //拿到十进制的数据去跟1做与运算，得到在二进制的形式下的每天登录天数
            if ((num & 1) == 0){
                //说明这天没有签到，结束统计
                break;
            }else {
                // 如果不为0，说明已签到，计数器+1
                count++;
            }
            // 把数字右移一位，抛弃最后一个bit位，继续下一个bit位
            num >>>= 1;
        }
        return count;
    }

    private User createUserWithPhone(String phone) {
        User user = new User();

        user.setPhone(phone);
        //设置昵称
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        //保存用户
        userMapper.saveUser(user);

        return user;
    }
}
